package com.hpe.controller.teacher;

import com.github.pagehelper.PageInfo;
import com.hpe.common.Const;
import com.hpe.dao.CourseMapper;
import com.hpe.dao.SClassMapper;
import com.hpe.pojo.*;
import com.hpe.service.*;
import com.hpe.util.ResponseCode;
import com.hpe.util.ServerResponse;
import com.hpe.util.ToolUtil;
import com.hpe.vo.ExamInFo;
import com.hpe.vo.ResetExamInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by chunjie on 2017/9/26.
 */

/**
 * @Author:XuShengJie
 * @Description:发布试卷Controller
 * @Date:14:35 2017/9/27
 */
@Controller
@RequestMapping("/teacher/exam")
public class TeacherExamController {

    @Autowired
    ScoreService scoreService;

    @Autowired
    SClassMapper sClassMapper;

    @Autowired
    CourseMapper courseMapper;

    @Autowired
    QuestionService questionService;

    @Autowired
    BigQuestionService bigQuestionService;

    @Autowired
    private ExamService testService;

    @Autowired
    ExamService examService;

    @Autowired
    DirectionService directionService;

    @Autowired
    ClassTeacherService classTeacherService;
    /**
     * @Author:XuShengJie
     * @Description:填写发布考试的信息页面,获取可以考试的课程
     * @Date:14:41 2017/9/27
     */
    @RequestMapping(method = RequestMethod.GET, value = "/get_course.do")
    @ResponseBody
    public ServerResponse<List<Course>> getCourse(HttpSession session) {
        //获取session中的teacher
        Teacher loginTeacher = (Teacher) session.getAttribute(Const.CURRENT_TEACHER);
        if (loginTeacher == null) {
            return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }
        return examService.getCourse();
    }

    /**
     * @description 根据type获取班级
     * @author Fujt
     * @date 2017/10/12 16:37
     */
    @PostMapping("/get_class_by_type.do")
    @ResponseBody
    public ServerResponse<List<SClass>> getSClassByType(int type) {
        return examService.getSClassByType(type);
    }


    /**
     * @Author:XuShengJie
     * @Description:组卷 存在题库题目不足的情况
     * //前台拿到的开始时间是long
     * @Date:15:25 2017/9/27
     */
    @RequestMapping(method = RequestMethod.POST, value = "/ready_add_exam.do")
    @ResponseBody
    public ServerResponse<Object> readyAddExam(ExamInFo examInFo,HttpSession session) {
        boolean courseResult = classTeacherService.judgmentClassOpenCourse(examInFo.getClassids(),examInFo.getCourseid());
        if(courseResult == false){
            return ServerResponse.createByErrorMsg("有班级和此课程未建立联系");
        }
        if((examInFo.getBigQuestionType1Num()==0&&examInFo.getScore1()!=0)||(examInFo.getBigQuestionType2Num()==0 &&examInFo.getScore2()!=0)){
            return ServerResponse.createByErrorMsg("请输入正确的分数,0道题目应该为0分");
        }
        ServerResponse returnResponse = examService.readyAddExam(examInFo,null,-1);
        if (returnResponse.getStatus() != 0) {
            return ServerResponse.createByErrorMsg(returnResponse.getMsg());
        } else {
            //把题目信息放到session中 在替换的时候防止重复
            StringBuffer stringBuffer = new StringBuffer();
            Map<String,Object> examMap = (Map<String,Object>)returnResponse.getData();
            List<Questions> questions = (List)examMap.get("question");
            List<BigQuestion> bqt1s = (List)examMap.get("bigt1Question");
            List<BigQuestion> bqt2s = (List)examMap.get("bigt2Question");
            for(Questions q:questions){
                stringBuffer.append(q.getId()+",");
            }
            if(stringBuffer.length()>0) {
                stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            }
            stringBuffer.append("@");
            for(int i = 0 ; i <bqt1s.size();i++){
                stringBuffer.append(bqt1s.get(i).getId()+",");
                if(i==bqt1s.size()-1){
                    stringBuffer.deleteCharAt(stringBuffer.length()-1);
                }
            }
            stringBuffer.append("@");
            for(int i = 0; i < bqt2s.size();i++){
                stringBuffer.append(bqt2s.get(i).getId()+",");
                if(i == bqt2s.size()-1){
                    stringBuffer.deleteCharAt(stringBuffer.length()-1);
                }
            }
            session.setAttribute("questionsid",stringBuffer);
            return ServerResponse.createBySuccess(returnResponse.getData());
        }
    }

    /**
     * @Author:XuShengJie
     * @Description:提交组卷
     * @Date:18:44 2017/9/27
     */
    @RequestMapping(method = RequestMethod.POST, value = "/add_exam.do")
    @ResponseBody
    public ServerResponse addExam(HttpSession session, Exam exam, @RequestParam(name = "questionid") String[] questionId,
                          @RequestParam(name = "bigquestiontype1id") String[] bigQuestionType1Id,
                          @RequestParam(name = "bigquestiontype2id") String[] bigQuestionType2Id,
                                  @RequestParam(name = "examId") Integer examId,
                                  @RequestParam(name = "stuId") String stuId) throws ParseException {
        Teacher teacher = (Teacher)session.getAttribute(Const.CURRENT_TEACHER);
        // 设置 发布的试卷信息的老师id
        exam.setTeacherid(teacher.getId());
        if(bigQuestionType1Id.length == 0){
            bigQuestionType1Id = new String[]{","};
        }
        if(bigQuestionType2Id.length == 0){
            bigQuestionType2Id = new String[]{","};
        }
        //设置题号
        exam.setQuestions(ToolUtil.threeArraytoString(questionId, bigQuestionType1Id, bigQuestionType2Id));
        //添加到service
            examService.addExam(exam,examId,stuId);
        return ServerResponse.createBySuccess();
    }

    /**
    * @Author:Liuli
    * @Description:获取所有试卷
    * @Date:9:11 2017/10/17
    */
    @RequestMapping(method = RequestMethod.GET, value = "/show_my_commit_exam.do")
    @ResponseBody
    public ServerResponse<PageInfo> showMyCommitExam(@RequestParam(name = "pageNum", defaultValue = "1") int pageNum,
                                                     @RequestParam(name = "pageSize", defaultValue = "5") int pageSize,
                                                     HttpSession session) {
        Teacher loginTeacher = (Teacher) session.getAttribute(Const.CURRENT_TEACHER);
        if (loginTeacher == null) {
            // return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return examService.showMyCommitExam(loginTeacher.getId(), pageNum, pageSize);
    }

    /**
     * @Author:XuShengJie
     * @Description:字符串转Date
     * @Date:11:17 2017/9/28
     */
    @InitBinder
    protected void init(HttpServletRequest request, ServletRequestDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }


    /**
     * @Author:XuShengJie
     * @Description:更换不满意的题目
     * @Date:10:34 2017/10/16
     */
    @RequestMapping(method = RequestMethod.POST, value = "/replace_question.do")
    @ResponseBody
    public ServerResponse<Object>  replaceQuestion(ExamInFo examInFo,HttpSession session,@RequestParam(name = "queType") Integer queType){
        String questions = ((StringBuffer)session.getAttribute("questionsid")).toString();
        ServerResponse returnResponse = examService.readyAddExam(examInFo,questions,queType);
        Map<String,Object> resultMap = (Map)returnResponse.getData();
        if (returnResponse.getStatus() != 0) {
            return ServerResponse.createByErrorMsg(returnResponse.getMsg());
        } else {
            String[] qids = questions.split("@");
            StringBuffer resultQid = new StringBuffer();
            if(queType == 0){
                resultQid.append(qids[0]);
                resultQid.append(","+((List<Questions>)resultMap.get("question")).get(0).getId());
                if(qids.length == 2){
                    resultQid.append("@"+qids[1]+"@");
                }else if(qids.length ==1) {
                    resultQid.append("@@");
                }else{
                        resultQid.append("@"+qids[1]+"@"+qids[2]);
                    }

            }else if(queType == 1){
                resultQid.append(qids[0]+"@");
                resultQid.append(qids[1]+","+((List<BigQuestion>)resultMap.get("bigt1Question")).get(0).getId());
                if(qids.length == 2){
                    resultQid.append("@");
                }else{
                    resultQid.append("@"+qids[2]);
                }
            }else if(queType == 2){
                resultQid.append(qids[0]+"@"+qids[1]+"@"+qids[2]+","+((List<BigQuestion>)resultMap.get("bigt2Question")).get(0).getId());
            }
            session.setAttribute("questionsid",resultQid);
            return ServerResponse.createBySuccess(returnResponse.getData());
        }
    }

    /**
     * @description 获取所有的方向
     * @author Fujt
     * @date 2017/10/12 16:00
     */
    @GetMapping("/get_all_directions.do")
    @ResponseBody
    public ServerResponse<List<Direction>> getAllDirections() {
        return directionService.getAllDirections();
    }

    
    /**
     * @Author:XuShengJie
     * @Description:查看一张试卷的详细情况
     * @Date:17:26 2017/10/16
     */
    @RequestMapping(method = RequestMethod.GET,value = "/find_this_exam.do")
    public ModelAndView findThisExam(@RequestParam("examId") int examId,ModelAndView modelAndView){
        //根据试卷id获取试卷信息
        ServerResponse<Exam> response =  testService.selectByPrimaryKey(Integer.valueOf(examId));
        Exam test=response.getData();

        String ques = test.getQuestions(); // 题目主键的字符串 2,3,4,5;12,1,3;123,123,1===> [2,3,4,5]
        //单选题
        String[] typesQue = ques.split(";");
        // 根据test试卷 questions , 查询单选题。
        List queList = questionService.findByIds(typesQue[0].split(","));
        //  查询  简答题 或 编程题。
        List que1List  = new ArrayList();
        if(typesQue.length >= 2 && typesQue[1].length() >= 1 ){
            String [] a = typesQue[1].split(",");
            que1List = bigQuestionService.findBigQuesByIds(typesQue[1].split(","),1);
        }
        List que2List  = new ArrayList();//编程题。
        if(typesQue.length >= 3 &&  typesQue[2].length() >= 1 ){
            String [] a = typesQue[2].split(",");
            que2List = bigQuestionService.findBigQuesByIds(typesQue[2].split(","),2);
        }
        //获取科目信息
        Course course = courseMapper.selectByPrimaryKey(test.getCourseid());
        //获取班级信息
        List<SClass> sClasses = new ArrayList<>();
        sClasses = sClassMapper.getListForIds(test.getClassids().split(","));

        //填装信息
        modelAndView.addObject("examinfo",test);
        modelAndView.addObject("queList",queList);
        modelAndView.addObject("queListSize", queList == null?0:queList.size());
        modelAndView.addObject("queList1", que1List);
        modelAndView.addObject("queListSize1", que1List == null?0: que1List.size());
        modelAndView.addObject("queList2", que2List);
        modelAndView.addObject("queListSize2",  que2List == null?0:que2List.size());
        modelAndView.addObject("course",course);
        modelAndView.addObject("sclass",sClasses);
        modelAndView.setViewName("/t-history-exam");
        return modelAndView;
    }
    
    /**
     * @Author:XuShengJie
     * @Description:获取补考试卷信息
     * @Date:19:55 2017/10/23
     */
    @RequestMapping(method = RequestMethod.GET,value = "/get_reset_examinfo.do")
    @ResponseBody
    public ServerResponse getResetInfo(){
        return scoreService.getRestetExamInfo();
    }
    
    /**
     * @Author:XuShengJie
     * @Description:补考组卷
     * @Date:10:25 2017/10/24
     */
    @RequestMapping(method = RequestMethod.POST,value = "/add_reset_exam.do")
    @ResponseBody
    public ServerResponse addResetExam(ResetExamInfoVo resetExamInfo){
        if((resetExamInfo.getBqt1num()==0&&resetExamInfo.getScore2()!=0)||(resetExamInfo.getBqt2num()==0 &&resetExamInfo.getScore3()!=0)){
            return ServerResponse.createByErrorMsg("请输入正确的分数,0道题目应该为0分");
        }
        return  examService.addResetExam(resetExamInfo);
    }
}
